package com.codeyang.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 描述: 登出controller
 *
 * @author CodeYang_Site
 * @version 2021/5/24 20:37
 */
@RestController
@Api(tags = "后台管理的登出接口")
@RequestMapping("sys")
public class SysLogoutController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 登出逻辑 :
     * 删除 持久化的redis存储
     *
     * @return
     */
    @ApiOperation("用户登出接口")
    @PostMapping("logout")
    public ResponseEntity<String> logout() {
        //1.拿到当前token
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //2.身份验证详细信息
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        //3.拿到token 这个没有前缀
        String jwt = details.getTokenValue();
        //从redis中删除
        //这个key 前缀是固定写法,现在先硬编码一下
        Boolean flag = redisTemplate.delete("oauth:jwt:" + jwt);
        return flag ? ResponseEntity.ok("登出成功") : ResponseEntity.badRequest().body("登出失败");

    }

}
